<script setup lang="ts">
import useCategoryStore from '@/store/modules/category.ts'
import { reqAttrList, reqDeleteAttr, reqSaveAttr } from '@/api/product/attr'
import { nextTick, onBeforeUnmount, reactive, ref, VNodeRef } from 'vue'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import type { Attr, AttrValue } from '@/api/product/attr/type.ts'
import type { ResponseData } from '@/api/type.ts'

const categoryStore = useCategoryStore()
const { c1Id, c2Id, c3Id } = storeToRefs(categoryStore)

const attrList = ref<Attr[]>([])
// 修改属性的数据
const attrParams = reactive<Attr>({
  id: '',
  attrName: '',
  attrValueList: [],
  categoryId: null,
  categoryLevel: 3,
})

const inputRefs = ref<any[]>([])

const scene = ref<number>(0)

const getAttrList = async () => {
  try {
    const { code, data, message }: ResponseData<Attr[]> = await reqAttrList(
      c1Id.value as number,
      c2Id.value as number,
      c3Id.value as number,
    )

    if (code === 200) {
      attrList.value = data
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const onAddAttrClick = () => {
  attrParams.categoryId = c3Id.value
  // 重置参数
  attrParams.id = null
  attrParams.attrName = ''
  attrParams.attrValueList = []
  scene.value = 1
}

const onAddAttrValueClick = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  })
  nextTick(() => {
    inputRefs.value[inputRefs.value.length - 1].focus()
  })
}

const onAttrSaveClick = async () => {
  const { code, message }: ResponseData<any> = await reqSaveAttr(attrParams)
  try {
    if (code === 200) {
      ElMessage.success(attrParams.id ? '修改成功' : '添加成功')
      scene.value = 0
      await getAttrList()
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

const onAttrCancelClick = () => {
  scene.value = 0
}

// 编辑属性点击回调
const onUpdateAttrClick = (row: Attr) => {
  scene.value = 1
  // 深拷贝
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

// 删除属性点击回调
const onDeleteAttrClick = async (id: number) => {
  const { code, message }: ResponseData<any> = await reqDeleteAttr(id)
  try {
    if (code === 200) {
      ElMessage.success('删除成功')
      scene.value = 0
      await getAttrList()
    } else {
      ElMessage.error(message)
    }
  } catch (err: any) {
    ElMessage.error(err?.message)
  }
}

// 删除属性值点击回调
const onDeleteAttrValueClick = ($index: number) => {
  attrParams.attrValueList.splice($index, 1)
}

const toEdit = (attrValue: AttrValue, $index: number) => {
  attrValue.flag = true
  nextTick(() => {
    inputRefs.value[$index].focus()
  })
}

const toLook = (row: AttrValue, $index: number) => {
  // 属性值不能为空
  if (!row.valueName) {
    ElMessage.warning('属性值不能为空')
    attrParams.attrValueList.splice($index, 1)
    return
  }

  // 属性值不能重复
  let repeat = attrParams.attrValueList.find((value) => {
    if (value !== row) {
      return value.valueName === row.valueName
    }
  })

  if (repeat) {
    ElMessage.warning('属性值不能重复')
    // attrParams.attrValueList.splice($index, 1)
    inputRefs.value[$index].focus()
    return
  }

  row.flag = false
}

onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<template>
  <div>
    <!-- 顶部分类选择 -->
    <el-card>
      <Category @getDataList="getAttrList" :disabled="scene === 1" />
    </el-card>
    <!-- 属性卡片 -->
    <el-card>
      <!-- 属性表格 -->
      <div v-show="scene === 0">
        <el-button
          type="primary"
          :disabled="!c3Id"
          icon="plus"
          @click="onAddAttrClick"
        >
          添加属性
        </el-button>
        <el-table :data="attrList" border>
          <el-table-column
            prop="id"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150"
          ></el-table-column>
          <el-table-column prop="attrValueList" label="属性值">
            <template #default="{ row }">
              <el-tag v-for="item in row.attrValueList" :key="item?.id">
                {{ item?.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                icon="edit"
                @click="onUpdateAttrClick(row)"
              ></el-button>
              <el-popconfirm
                :title="`确认删除属性：${row.attrName}？`"
                icon="WarningFilled"
                confirm-button-text="确认"
                cancel-button-text="取消"
                width="200"
                @confirm="onDeleteAttrClick(row?.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <template #empty></template>
        </el-table>
      </div>
      <!-- 添加属性表单 -->
      <div v-show="scene === 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              v-model="attrParams.attrName"
              placeholder="请输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-row>
          <el-button
            type="primary"
            icon="plus"
            @click="onAddAttrValueClick"
            :disabled="!attrParams.attrName"
          >
            添加属性值
          </el-button>
          <el-button>取消</el-button>
        </el-row>
        <el-table :data="attrParams.attrValueList" border>
          <el-table-column
            type="index"
            label="序号"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column prop="valueName" label="属性值">
            <template #default="{ row, $index }">
              <el-input
                v-if="row.flag"
                v-model="row.valueName"
                :ref="(el: VNodeRef) => (inputRefs[$index] = el)"
                size="small"
                placeholder="请输入属性值"
                @blur="toLook(row, $index)"
              />
              <div v-else @click="toEdit(row, $index)">
                {{ row?.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ $index }">
              <el-button
                type="danger"
                size="small"
                icon="delete"
                @click="onDeleteAttrValueClick($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-button
            type="primary"
            :disabled="!attrParams.attrName"
            @click="onAttrSaveClick"
          >
            保存
          </el-button>
          <el-button @click="onAttrCancelClick">取消</el-button>
        </el-row>
      </div>
    </el-card>
  </div>
</template>
<style lang="scss">
.el-tag {
  margin: 0 5px;
}
</style>
<style scoped lang="scss"></style>
